//
//  OAuthViewController.swift
//  SinaWeibo25
//
//  Created by David on 16/3/7.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func defaultAccount() {
        //需要在webView中 设置账号和密码
        let jsString = "document.getElementById('userId').value = '13716046468', document.getElementById('passwd').value = '181856928q' "
        //通过字符串来执行javascrip 代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    override func loadView() {
        view = webView
        
        //设置设置不透明
        webView.opaque = false
        
        //设置代理
        webView.delegate = self
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置导航条
        setNavBar()
        
        
        //手动创建的视图控制器  根视图的背景色 是 透明的
        view.backgroundColor  = UIColor.whiteColor()
        
        
        //加载授权页面
        loadOAuthPage()
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    
    //加载授权页面  -> 用户需要输入用户名和密码 完成登录授权
    private func loadOAuthPage() {
        //1. urlString
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)"  + "&redirect_uri=\(redirect_uri)"
        //2.NSURL
        let url = NSURL(string: urlString)
        
        //3.NSURLRequest
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAccount")
    }
    
}


//webView协议方法的转么拿到扩展
extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //一般协议方法 返回值 为 bool类型 默认返回yes  想对应的控件就能够正常工作 反之  不能正常工作
    //在这个协议方法中 可以监测到webView每次加载新的页面发起的网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //包含了回调地址的url中一定包好了code字段 
        //if xxxx.rangOfString .location != NSNotFound
        if urlString.containsString("code") {
            //不加载网页
            
            //在这个地方需要获取url中包好的code  使用code 获取token
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            //将String 转换为NSString 
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            //使用code 来获取token
            
            UserAccount.shareAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                
                //登录成功  销毁当前页面  类与类之间的通讯
               
                
                //切换根视图控制器
//                UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
                
               
                
                 self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    //通知是同步的还是异步的
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: "oauth")
                    
                    
                    print("come here")
                 })
                
            })
            return false
        }
        
        return true
    }
    
}
